package com.lyf.service;

import com.lyf.annotation.CacheRefresh;
import com.lyf.redis.RedisUtil;
import lombok.extern.log4j.Log4j2;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * @author hailin.
 * @date 2020/9/8 17:33
 **/
@Component
@Log4j2
public class CacheRefreshService {

    @Autowired
    private RedisUtil redisUtil;

    private final String TTL = "_ttl";

    /**
     * 异步添加缓存
     *
     * @param key
     * @param value
     * @param cacheRefresh
     */
    @Async
    public void addCache(String key, Object value, CacheRefresh cacheRefresh) {
        log.info("[addCache] key: {}", key);
        String ttlKey = key + TTL;
        redisUtil.set(ttlKey, System.currentTimeMillis(), cacheRefresh.expire());
        redisUtil.set(key, value, 7*24*60*60l);
    }

    /**
     * 异步更新缓存
     *
     * @param key
     * @param pjp
     * @param cacheRefresh
     * @throws Throwable
     */
    @Async
    public void updateCache(String key, ProceedingJoinPoint pjp, CacheRefresh cacheRefresh) throws Throwable {
        String ttlKey = key + TTL;
        long expire = redisUtil.getExpire(ttlKey);
        if (expire <= cacheRefresh.refresh()) {
            redisUtil.set(ttlKey, 1, cacheRefresh.expire());
            log.info("[updateCache] key: {} expire: {}", key, expire);
            redisUtil.set(key, pjp.proceed());
        }
    }


}